package com.example.service.impl;

import com.example.result.ReturnCode;
import com.example.result.ReturnResult;
import com.example.service.IBOMService;
import com.example.service.IPartService;
import com.example.vo.*;
import com.huawei.innovation.rdm.coresdk.basic.dto.GenericLinkQueryDTO;
import com.huawei.innovation.rdm.coresdk.basic.dto.ObjectReferenceParamDTO;
import com.huawei.innovation.rdm.coresdk.basic.dto.PersistObjectIdModifierDTO;
import com.huawei.innovation.rdm.coresdk.basic.enums.ConditionType;
import com.huawei.innovation.rdm.coresdk.basic.vo.QueryCondition;
import com.huawei.innovation.rdm.coresdk.basic.vo.QueryRequestVo;
import com.huawei.innovation.rdm.coresdk.basic.vo.RDMPageVO;
import com.huawei.innovation.rdm.lwxminibom.delegator.BOMLinkDelegator;
import com.huawei.innovation.rdm.lwxminibom.delegator.BOMUsesOccurrenceDelegator;
import com.huawei.innovation.rdm.lwxminibom.delegator.PartDelegator;
import com.huawei.innovation.rdm.lwxminibom.dto.entity.BOMUsesOccurrenceCreateDTO;
import com.huawei.innovation.rdm.lwxminibom.dto.entity.BOMUsesOccurrenceUpdateDTO;
import com.huawei.innovation.rdm.lwxminibom.dto.entity.BOMUsesOccurrenceViewDTO;
import com.huawei.innovation.rdm.lwxminibom.dto.entity.PartViewDTO;
import com.huawei.innovation.rdm.lwxminibom.dto.relation.BOMLinkCreateDTO;
import com.huawei.innovation.rdm.lwxminibom.dto.relation.BOMLinkUpdateDTO;
import com.huawei.innovation.rdm.lwxminibom.dto.relation.BOMLinkViewDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class BOMService implements IBOMService {

    Logger logger= LoggerFactory.getLogger(BOMService.class);

    @Autowired
    private PartDelegator partDelegator;

    @Autowired
    BOMLinkDelegator bomLinkDelegator;

    @Autowired
    BOMUsesOccurrenceDelegator bomUsesOccurrenceDelegator;

    @Autowired
    IPartService iPartService;


    @Override
    public ReturnResult querySonItem(BOMLinkQuerySonItemParamVO bomLinkQuerySonItemParamVO) {
        String versionId= bomLinkQuerySonItemParamVO.getVersionId();
        long version_id=Long.parseLong(versionId);
        logger.info("BOMService.query"+"   "+"查询的versionId:"+version_id);

        QueryRequestVo queryRequestVo=new QueryRequestVo();
        QueryCondition queryCondition=new QueryCondition();

        queryCondition.addCondition("source.id", ConditionType.EQUAL,version_id);
        queryCondition.setJoiner("or");
        queryRequestVo.setFilter(queryCondition);

        List<BOMLinkViewDTO> bomLinkViewDTOS = bomLinkDelegator.find(queryRequestVo, new RDMPageVO());
        if(bomLinkViewDTOS==null||bomLinkViewDTOS.isEmpty()){
            return new ReturnResult(ReturnCode.GET_ERR,"查询到的BOMLink为空",null);
        }

        List<BOMLinkQuerySonItemResultVO> res=new ArrayList<>();
        for(BOMLinkViewDTO bomLinkViewDTO:bomLinkViewDTOS){
            BOMLinkQuerySonItemResultVO bomLinkQuerySonItemResultVO =new BOMLinkQuerySonItemResultVO();
            bomLinkQuerySonItemResultVO.setBomLinkId(bomLinkViewDTO.getId().toString());
            bomLinkQuerySonItemResultVO.setSourcePartVersionId(bomLinkViewDTO.getSource().getId().toString());
            bomLinkQuerySonItemResultVO.setSourceName(bomLinkViewDTO.getSource().getName());
            bomLinkQuerySonItemResultVO.setTargetPartMasterId(bomLinkViewDTO.getTarget().getId().toString());
            bomLinkQuerySonItemResultVO.setTargetName(bomLinkViewDTO.getTarget().getName());
            bomLinkQuerySonItemResultVO.setQuantity(bomLinkViewDTO.getQuantity());

            //查找位号
            QueryRequestVo queryRequestVo2=new QueryRequestVo();
            QueryCondition queryCondition2=new QueryCondition();
            queryCondition2.setJoiner("or");
            queryRequestVo2.setFilter(queryCondition2);

            queryCondition2.addCondition("bomLink.id",ConditionType.EQUAL,bomLinkViewDTO.getId());
            List<BOMUsesOccurrenceViewDTO> bomUsesOccurrenceViewDTOS = bomUsesOccurrenceDelegator.find(queryRequestVo2, new RDMPageVO());

            if(bomUsesOccurrenceViewDTOS==null||bomUsesOccurrenceViewDTOS.isEmpty()){
                res.add(bomLinkQuerySonItemResultVO);
            }else{
                for(BOMUsesOccurrenceViewDTO bomUsesOccurrenceViewDTO:bomUsesOccurrenceViewDTOS){
                    //深拷贝
                    BOMLinkQuerySonItemResultVO newBOMLinkQuerySonItemResultVo = bomLinkQuerySonItemResultVO.clone();
                    newBOMLinkQuerySonItemResultVo.setReferenceDesignator(bomUsesOccurrenceViewDTO.getReferenceDesignator());
                    res.add(newBOMLinkQuerySonItemResultVo);
                }
            }
        }

        return new ReturnResult(ReturnCode.GET_OK,"查询BOMLink子项成功",res);
    }

    @Override
    public ReturnResult queryParentItem(BOMLinkQueryParentItemParamVO bomLinkQueryParentItemParamVO) {
        String sonItemId=bomLinkQueryParentItemParamVO.getSonItemId();
        logger.info("BOMService.queryParentItem"+"   "+"sonItemId"+sonItemId);

        QueryRequestVo queryRequestVo=new QueryRequestVo();
        QueryCondition queryCondition=new QueryCondition();

        queryCondition.addCondition("target.id", ConditionType.EQUAL,sonItemId);
        queryCondition.setJoiner("or");
        queryRequestVo.setFilter(queryCondition);

        List<BOMLinkViewDTO> bomLinkViewDTOS = bomLinkDelegator.find(queryRequestVo, new RDMPageVO());
        if(bomLinkViewDTOS==null||bomLinkViewDTOS.isEmpty()){
            return new ReturnResult(ReturnCode.GET_ERR,"查询到的父项为空",null);
        }

        Set<Long> hashSet=new HashSet<>();
        for(BOMLinkViewDTO bomLinkViewDTO:bomLinkViewDTOS){
            hashSet.add(bomLinkViewDTO.getSource().getId());
        }

        List<PartQueryResultVO> result=new ArrayList<>();
        for(Long versionId:hashSet){
            List<PartQueryResultVO> partQueryResultVOS = iPartService.queryByVersionId(versionId);
            result.addAll(partQueryResultVOS);
        }
        return new ReturnResult(ReturnCode.GET_OK,"查询父项成功",result);
    }

    @Override
    public ReturnResult create(BOMLinkCreateParamVO bomLinkCreateParamVO) {

        Long sourceId = Long.valueOf(bomLinkCreateParamVO.getSourceId());
        Long targetId = Long.valueOf(bomLinkCreateParamVO.getTargetId());
        Double quantity = bomLinkCreateParamVO.getQuantity();

        QueryRequestVo queryRequestVo = new QueryRequestVo();
        QueryCondition queryCondition = new QueryCondition();
        queryCondition.setJoiner("and");
        queryCondition.addCondition("master.id",ConditionType.EQUAL, sourceId);
        queryCondition.addCondition("latest",ConditionType.EQUAL, true);
        queryRequestVo.setFilter(queryCondition);
        List<PartViewDTO> query = partDelegator.find(queryRequestVo, new RDMPageVO());
        if(query == null || query.isEmpty()){
            return new ReturnResult(ReturnCode.GET_ERR, "查询为空", null);
        }
        Long sourceVersionId = 0L;
        for(PartViewDTO partViewDTO:query){
            sourceVersionId = partViewDTO.getId();
        }
        String referenceDesignator = bomLinkCreateParamVO.getReferenceDesignator();
        logger.info("BOMService.create第一阶段"+"   "+"开始创建BOMLink");
        BOMLinkCreateDTO bomLinkCreateDTO = new BOMLinkCreateDTO();
        ObjectReferenceParamDTO sourceParamDTO = new ObjectReferenceParamDTO();
        sourceParamDTO.setId(sourceVersionId);
        ObjectReferenceParamDTO targetParamDTO = new ObjectReferenceParamDTO();
        targetParamDTO.setId(targetId);
        bomLinkCreateDTO.setSource(sourceParamDTO);
        bomLinkCreateDTO.setTarget(targetParamDTO);
        bomLinkCreateDTO.setQuantity(BigDecimal.valueOf(quantity));
        BOMLinkViewDTO bomLinkViewDTO = bomLinkDelegator.create(bomLinkCreateDTO);
        Long id = bomLinkViewDTO.getId();

        logger.info("BOMService.create第二阶段"+"   "+"开始创建BOMUsesOccurrence");
        BOMUsesOccurrenceCreateDTO bomUsesOccurrenceCreateDTO = new BOMUsesOccurrenceCreateDTO();
        ObjectReferenceParamDTO bomlinkParamDTO = new ObjectReferenceParamDTO();
        bomlinkParamDTO.setId(id);
        bomUsesOccurrenceCreateDTO.setBomLink(bomlinkParamDTO);
        bomUsesOccurrenceCreateDTO.setReferenceDesignator(referenceDesignator);
        BOMUsesOccurrenceViewDTO bomUsesOccurrenceViewDTO = bomUsesOccurrenceDelegator.create(bomUsesOccurrenceCreateDTO);
        return new ReturnResult(ReturnCode.GET_OK,"创建子项成功",null);
    }

    @Override
    public ReturnResult delete(String bomLinkId) {
        long bom_link_id=Long.parseLong(bomLinkId);
        logger.info("BOMService.delete"+"   "+"开始删除bomLink:"+bom_link_id);
        QueryRequestVo queryRequestVo=new QueryRequestVo();
        QueryCondition queryCondition=new QueryCondition();
        queryCondition.setJoiner("and");
        queryCondition.addCondition("bomLink.id",ConditionType.EQUAL,bom_link_id);
        queryRequestVo.setFilter(queryCondition);
        List<BOMUsesOccurrenceViewDTO> bomUsesOccurrenceViewDTOS = bomUsesOccurrenceDelegator.find(queryRequestVo, new RDMPageVO());

        if(bomUsesOccurrenceViewDTOS != null){
            for(BOMUsesOccurrenceViewDTO bomUsesOccurrenceViewDTO :bomUsesOccurrenceViewDTOS){
                Long id = bomUsesOccurrenceViewDTO.getId();
                PersistObjectIdModifierDTO persistObjectIdModifierDTO = new PersistObjectIdModifierDTO();
                persistObjectIdModifierDTO.setId(id);
                bomUsesOccurrenceDelegator.delete(persistObjectIdModifierDTO);
            }
        }
        PersistObjectIdModifierDTO persistObjectIdModifierDTO = new PersistObjectIdModifierDTO();
        persistObjectIdModifierDTO.setId(bom_link_id);
        bomLinkDelegator.delete(persistObjectIdModifierDTO);

        return new ReturnResult(ReturnCode.DELETE_OK,"删除子项成功",null);
    }


    @Override
    public ReturnResult update(BomLinkUpdateParamVO bomLinkUpdateParamVO) {
        logger.info("BOMService.updateQuantity"+"   "+"更新bomLink数量");
        Long bomLinkId = Long.valueOf(bomLinkUpdateParamVO.getBomLinkId());
        Long quantity = bomLinkUpdateParamVO.getQuantity();
        BOMLinkUpdateDTO bomLinkUpdateDTO = new BOMLinkUpdateDTO();
        bomLinkUpdateDTO.setQuantity(BigDecimal.valueOf(quantity));
        bomLinkUpdateDTO.setId(bomLinkId);
        bomLinkDelegator.update(bomLinkUpdateDTO);
        logger.info("BOMService.updateReferenceDesignator"+"   "+"更新位号");
        QueryRequestVo queryRequestVo=new QueryRequestVo();
        QueryCondition queryCondition=new QueryCondition();
        queryCondition.setJoiner("and");
        queryCondition.addCondition("bomLink.id",ConditionType.EQUAL,bomLinkId);
        queryRequestVo.setFilter(queryCondition);
        List<BOMUsesOccurrenceViewDTO> bomUsesOccurrenceViewDTOS = bomUsesOccurrenceDelegator.find(queryRequestVo, new RDMPageVO());
        String referenceDesignator = bomLinkUpdateParamVO.getReferenceDesignator();
        for(BOMUsesOccurrenceViewDTO bomUsesOccurrenceViewDTO :bomUsesOccurrenceViewDTOS){
            BOMUsesOccurrenceUpdateDTO bomUsesOccurrenceUpdateDTO = new BOMUsesOccurrenceUpdateDTO();
            Long id = bomUsesOccurrenceViewDTO.getId();
            bomUsesOccurrenceUpdateDTO.setId(id);
            bomUsesOccurrenceUpdateDTO.setReferenceDesignator(referenceDesignator);
            bomUsesOccurrenceDelegator.update(bomUsesOccurrenceUpdateDTO);
        }
        return new ReturnResult(ReturnCode.UPDATE_OK,"更新子项成功",null);
    }

    @Override
    public BOMLinkListVO listQuery(BOMLinkListVO bomLinkListVO) {
        QueryRequestVo queryRequestVo = new QueryRequestVo();
        QueryCondition queryCondition = new QueryCondition();
        queryCondition.setJoiner("and");
        queryCondition.addCondition("master.id",ConditionType.EQUAL, bomLinkListVO.getPartId());
        queryCondition.addCondition("latest",ConditionType.EQUAL, true);
        queryRequestVo.setFilter(queryCondition);
        List<PartViewDTO> query = partDelegator.find(queryRequestVo, new RDMPageVO());
        Long sourceVersionId = 0L;
        for(PartViewDTO partViewDTO:query){
            sourceVersionId = partViewDTO.getId();
        }
        QueryRequestVo queryRequestVo1 = new QueryRequestVo();
        QueryCondition queryCondition1 = new QueryCondition();
        queryCondition1.setJoiner("and");
        queryCondition1.addCondition("source.id",ConditionType.EQUAL, sourceVersionId);
        queryRequestVo1.setFilter(queryCondition1);
        List<BOMLinkViewDTO> bomLinkViewDTOList = bomLinkDelegator.find(queryRequestVo1,new RDMPageVO());
        bomLinkListVO.setChildren(new ArrayList<>());
            if(bomLinkViewDTOList != null && !bomLinkViewDTOList.isEmpty()){
                for(BOMLinkViewDTO bomLinkViewDTO : bomLinkViewDTOList){
                    BOMLinkListVO node = new BOMLinkListVO(String.valueOf(bomLinkViewDTO.getTarget().getId()),bomLinkViewDTO.getTarget().getNumber(),bomLinkViewDTO.getTarget().getName(),null);
                    bomLinkListVO.addChildren(listQuery(node));
                }
            }
//        }
        return bomLinkListVO;
    }

    @Override
    public BOMLinkListVO findDetail(String masterId) {
        logger.info("BOMService.findDetail,传入的masterId为 "+ masterId +" 查询bom清单");
        BOMLinkListVO bomLinkListVO = new BOMLinkListVO();
        QueryRequestVo queryRequestVo = new QueryRequestVo();
        QueryCondition queryCondition = new QueryCondition();
        queryCondition.setJoiner("and");
        queryCondition.addCondition("master.id",ConditionType.EQUAL, Long.valueOf(masterId));
        queryCondition.addCondition("latest",ConditionType.EQUAL, true);
        queryRequestVo.setFilter(queryCondition);
        List<PartViewDTO> query = partDelegator.find(queryRequestVo, new RDMPageVO());
        for(PartViewDTO partViewDTO:query){
            bomLinkListVO.setName(partViewDTO.getMaster().getName());
            bomLinkListVO.setNumber(partViewDTO.getMaster().getNumber());
        }
        bomLinkListVO.setPartId(masterId);
        return bomLinkListVO;
    }
}
